import sys, os, amara, posixpath
from optparse import OptionParser
from brightcontent.core.store import COMMON_PREFIXES, ATOM10_NS, flatfile_repository, ENVELOPE_XML_FILE, OMIT_FROM_SLUG_PAT
from Ft.Xml.Xslt import Transform
from Ft.Xml import CreateInputSource
from Ft.Lib import Uri
from brightcontent.plugins.staticfiles import fget
from brightcontent.util import fixup_namespaces
from amara.binderytools import quick_xml_scan
from wsgixml.applyxslt import setup_xslt_params

BC_NS = 'http://brightcontent.net/ns/'

if __name__=="__main__":

    usage = '%s [input file or url] [output directory] [OPTIONS]'

    parser = OptionParser()
    parser.add_option('-u', '--base-url', dest='base_url')

    (options, args) = parser.parse_args()
    if len(args) < 2:
        print
        print usage
        print
        sys.exit(1)

    input_file_or_url = args[0]
    collection = args[1]
    if not options.base_url:
        base_url = 'http://localhost:8080/blog'
    else:
        base_url = options.base_url.strip('/')
    print 'Using "%s" for the base url.' % base_url

    try:
        os.makedirs(collection)
    except OSError:
        pass            

    src = input_file_or_url
    xsltfn = fget('import.xslt')
    xslt = file(xsltfn, 'r').read()

    xslt_uri = Uri.OsPathToUri(os.path.abspath('bc-functions.xslt'))
    
    params = { u'base_url' : unicode(base_url),
               u'collection_url' : unicode(collection),
               u'functions-xslt' : unicode(xslt_uri) }
    doc = amara.parse(Transform(src, xslt,
            params=setup_xslt_params(BC_NS, params)), prefixes=COMMON_PREFIXES)

    envelope = amara.create_document(u"feed", ns=ATOM10_NS)
    for nonentry in doc.feed.xml_xpath(u'*[not(self::atom:entry)]'):
        envelope.feed.xml_append(nonentry)
    if not os.path.isdir(collection):
        os.mkdir(collection)
    f = open(os.path.join(collection, ENVELOPE_XML_FILE), 'w')        
    # fixup_namespaces(doc)
    f.write(envelope.xml(indent=u"yes"))
    f.close()
    store = flatfile_repository(flatfile_storedir=collection)
    
    for entry in doc.feed.entry:
        slug = str(entry.title)
        slug = OMIT_FROM_SLUG_PAT.sub('_', slug).decode('utf-8')
        # assume the base_iri contains the collection...
        pub_date = amara.binderytools.parse_isodate(str(entry.published))
        # iri_id = posixpath.join(base_url, pub_date.strftime('%Y/%m/%d'), slug) + '.atom'
        iri_id = entry.id
        store.create_entry(entry.xml(indent=True), slug)
        print "Created: %s" % iri_id

